<template>
    <div class="common-layout">
        <el-container>
            <el-aside>
                <div class="left">
                    <SvgIcon class="svgs" icon-class="jing"></SvgIcon>
                    <el-input v-model="input" style="width: 200px" placeholder="部门名称" />
                </div>
                <div class="left_bom">
                    <el-tree style="max-width: 600px" :data="leftList[0]" :props="defaultProps"
                        @node-click="handleNodeClick" />
                </div>
            </el-aside>
            <el-container>
                <el-header>
                    <div class="search-container">
                        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                            <el-form-item label="关键字" prop="keywords">
                                <el-input v-model="queryParams.keywords" placeholder="部门名称"
                                    @keyup.enter="handleQuery" />
                            </el-form-item>

                            <el-form-item label="部门状态" prop="status">
                                <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[100px]">
                                    <el-option :value="1" label="正常" />
                                    <el-option :value="0" label="禁用" />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button class="filter-item" type="primary" @click="handleQuery">
                                    <i-ep-search />
                                    搜索
                                </el-button>
                                <el-button @click="handleResetQuery">
                                    <i-ep-refresh />重置
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-header>
                <el-main>
                    <el-button type="success" @click="openDialog(0, undefined)"><i-ep-plus />新增</el-button>
                    <el-button type="danger" @click="handleDelete()"
                        :disabled="ids.length === 0"><i-ep-delete />删除</el-button>
                    <el-table :data="deptList" row-key="id" style="width: 100%"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column prop="name" label="部门名称" width="200" align="center" />
                        <el-table-column prop="status" label="状态" width="100" align="center">
                            <template #default="scope">
                                <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
                                <el-tag v-else type="info">禁用</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sort" label="排序" width="100" align="center" />
                        <el-table-column fixed="right" label="操作" width="200" align="center">
                            <template #default="scope">
                                <el-button link type="primary" size="small"
                                    @click.stop="openDialog(scope.row.id, undefined)">
                                    <i-ep-plus />新增
                                </el-button>
                                <el-button link type="primary" size="small"
                                    @click.stop="openDialog(scope.row.parentId, scope.row.id)">
                                    <i-ep-edit />编辑
                                </el-button>
                                <el-button link type="primary" size="small" @click.stop="handleDelete(scope.row.id)">
                                    <i-ep-delete />删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @closed="closeDialog">
                        <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="80px">
                            <el-form-item label="上级部门" prop="parentId">
                                <el-tree-select v-model="formData.parentId" placeholder="选择上级部门" :data="deptOptions"
                                    filterable check-strictly :render-after-expand="false" />
                            </el-form-item>
                            <el-form-item label="部门名称" prop="name">
                                <el-input v-model="formData.name" placeholder="请输入部门名称" />
                            </el-form-item>
                            <el-form-item label="显示排序" prop="sort">
                                <el-input-number v-model="formData.sort" controls-position="right" style="width: 100px"
                                    :min="0" />
                            </el-form-item>
                            <el-form-item label="部门状态">
                                <el-radio-group v-model="formData.status">
                                    <el-radio :label="1">正常</el-radio>
                                    <el-radio :label="0">禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-form>

                        <template #footer>
                            <div class="dialog-footer">
                                <el-button type="primary" @click="handleSubmit"> 确 定 </el-button>
                                <el-button @click="closeDialog"> 取 消 </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
// 调用SVG
import SvgIcon from '@/components/SvgIcon/index.vue'

// 调用接口
import { getList, getOptions, getFormData, add, update, deleteByIds } from '@/api/dept/index'
// 调用类型
import type { DeptQuery, DeptVO, DeptForm } from '@/api/dept/model'
import type { OptionType } from 'element-plus/es/components/select-v2/src/select.types.mjs';
const queryFormRef = ref(ElForm);
const deptFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const dialog = reactive({
    title: "",
    visible: false,
});
const queryParams = reactive<DeptQuery>({});
const deptList = ref<DeptVO[]>();
const deptOptions = ref<OptionType[]>();
const formData = reactive<DeptForm>({
    status: 1,
    parentId: 0,
    sort: 1,
});
const rules = reactive({
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
    name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});
const input = ref('')
// 获取部门
const leftList = ref([])
const getFen = async () => {
    const res = await getList()
    leftList.value.push(res)

}
const defaultProps = {
    children: 'children',
    label: 'name',
}
/** 查询 */
async function handleQuery() {
    loading.value = true;
    await getList(queryParams).then((data) => {
        deptList.value = data;
        console.log(deptList.value);
        loading.value = false;
    });
}


/**重置查询 */
function handleResetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}
/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
    ids.value = selection.map((item: any) => item.id);
}
/** 获取部门下拉数据  */
async function loadDeptOptions() {
    await getOptions().then((data) => {
        deptOptions.value = [
            {
                value: 0,
                label: "顶级部门",
                children: data,
            },
        ];
    });
}

/**
 * 打开弹窗
 *
 * @param parentId 父部门ID
 * @param deptId 部门ID
 */
async function openDialog(parentId?: number, deptId?: number) {
    await loadDeptOptions();
    dialog.visible = true;
    if (deptId) {
        dialog.title = "修改部门";
        await getFormData(deptId).then((data) => {
            Object.assign(formData, data);
        });
    } else {
        dialog.title = "新增部门";
        formData.parentId = parentId ?? 0;
    }
}

/** 表单提交 */
function handleSubmit() {
    deptFormRef.value.validate((valid: any) => {
        if (valid) {
            const deptId = formData.id;
            loading.value = true;
            if (deptId) {
                update(deptId, formData)
                    .then(() => {
                        ElMessage.success("修改成功");
                        closeDialog();
                        handleQuery();
                    })
                    .finally(() => (loading.value = false));
            } else {
                add(formData)
                    .then(() => {
                        ElMessage.success("新增成功");
                        closeDialog();
                        handleQuery();
                    })
                    .finally(() => (loading.value = false));
            }
        }
    });
}

/** 删除部门 */
function handleDelete(deptId?: number) {
    const deptIds = [deptId || ids.value].join(",");

    if (!deptIds) {
        ElMessage.warning("请勾选删除项");
        return;
    }

    ElMessageBox.confirm(`确认删除已选中的数据项?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteByIds(deptIds).then(() => {
            ElMessage.success("删除成功");
            handleResetQuery();
        });
    });
}

/** 关闭弹窗 */
function closeDialog() {
    dialog.visible = false;
    resetForm();
}

/** 重置表单  */
function resetForm() {
    deptFormRef.value.resetFields();
    deptFormRef.value.clearValidate();

    formData.id = undefined;
    formData.parentId = 0;
    formData.status = 1;
    formData.sort = 1;
}

const handleNodeClick = () => {

}

onMounted(() => {
    handleQuery();
    getFen()
});
</script>

<style scoped>
.el-aside {
    background-color: white;
    width: 220px;
    padding-bottom: 30px;
    padding: 0 10px;
    box-sizing: border-box;
}

.left {
    position: relative;
    text-align: center;
    padding-top: 20px;
    box-sizing: border-box;
}

.left_bom {
    margin-top: 10px;
}

::v-deep.el-input input {
    padding-left: 20px;
    box-sizing: border-box;
}

.svgs {
    position: absolute;
    z-index: 1;
    top: 28px;
    left: 10px;
}



.el-header,
.el-main {
    margin-left: 20px;
    background-color: white;
}

.el-main {
    margin-top: 10px;
}

.el-header {
    height: 50px;
    padding: 10px 20px;
    box-sizing: border-box;
}
</style>